import torch

X = [1.0, 2.0, 3.0]
Y = [2.0, 4.0, 6.0]

w = torch.Tensor([1.0])
w.requires_grad = True

def forward(x):
    return w * x

def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) ** 2

print("训练前预测值：", 4, forward(4).item())

for epoch in range(100):
    for x, y in zip(X, Y):
        l = loss(x, y)  # 计算损失，构建计算图
        l.backward() # 利用反向传播，计算每个计算的梯度
        print("\t grad:", x, y, w.grad.item())
        w.data = w.data - 0.01 * w.grad.data  # 更新参数的梯度

        w.grad.data.zero_()

    print("epoch:", epoch, "loss:", l.item())

print("训练后预测值：", 4, forward(4).item())
